import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8005',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('响应错误:', error)
    return Promise.reject(error)
  }
)

// 获取PLC数据
export const getPLCData = async () => {
  try {
    const response = await api.get('/api/v1/plc/data')
    return response.data
  } catch (error) {
    console.error('获取PLC数据失败:', error)
    throw error
  }
}

export const mapPLCDataToFrontend = (apiResponse) => {
  // API返回的数据在data字段中
  const plcData = apiResponse.data || {};
  
  return {
    // 产品信息
    infoData: {
      stationName: plcData.station_name?.value || '',
      project_name: plcData.project_name?.value || '',
      productNumber: plcData.product_number?.value || '',
      count: plcData.count?.value || '',
      trace_barcode: plcData.trace_barcode?.value || '',
      operator: plcData.operator?.value || '',
      rtpVersion: plcData.rtp_version?.value || '',
      software_version: plcData.software_version?.value || '',
      productStatus: plcData.product_status?.value || '',
      qualifiedCount: plcData.qualified_count?.value || '',
      unqualifiedCount: plcData.unqualified_count?.value || 0,
      concessionCount: plcData.concession_count?.value || ''
    },
    // 测试项信息
    testItems: {
      motorId: plcData.Motor_id?.value || '',
      controllerId: plcData.EDCU_id?.value || '',
      closingForceTest: plcData.Dielectric_test?.value || false,
      antiPinchTest: plcData.Obstacle_test?.value || false,
      openTime: plcData.Open_time?.value || 0,
      harnessBarcode: plcData.Wiring_barcode?.value || '',
      pushForce: plcData.Push_force?.value || 0,
      closeTime: plcData.Close_time?.value || 0,
      pullForce: plcData.Pull_force?.value || 0
    },
    // 时间戳
    timestamp: apiResponse.timestamp
  };
};

// 获取工序步骤数据
export const getOperations = async () => {
  try {
    const response = await api.get('/api/v1/operations')
    const data = response.data
    
    // 映射后端数据格式到前端期望的格式
    if (data.status === 'success' && data.operations) {
      const mappedOperations = data.operations.map(op => ({
        step: op.operation_number,
        operation: op.operation_name,
        sub_operations: op.sub_operations ? op.sub_operations.map(subOp => ({
          step: subOp.sub_number,
          operation: subOp.sub_name
        })) : []
      }))
      return mappedOperations
    }
    
    return []
  } catch (error) {
    console.error('获取工序步骤失败:', error)
    // 如果是HTTP错误且有响应数据，尝试获取后端的具体错误信息
    if (error.response && error.response.data) {
      const errorData = error.response.data
      if (typeof errorData === 'object' && errorData.detail) {
        // 后端返回的详细错误信息
        throw new Error(errorData.detail)
      } else if (typeof errorData === 'string') {
        throw new Error(errorData)
      }
    }
    throw error
  }
}

// 上传Excel文件
export const uploadExcel = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await api.post('/api/v1/upload-excel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  } catch (error) {
    console.error('上传Excel文件失败:', error)
    throw error
  }
}

// 扫码模拟测试API
export const testScanSimulation = async () => {
  try {
    const response = await api.post('/api/v1/scanner/test-simulation')
    return response.data
  } catch (error) {
    console.error('扫码测试失败:', error)
    throw error
  }
}

// 设置扫码枪监控就绪状态
export const setScannerReady = async () => {
  try {
    const response = await api.post('/api/v1/scanner/set-ready')
    return response.data
  } catch (error) {
    console.error('设置允许扫码状态失败:', error)
    throw error
  }
}

// 获取扫码枪监控就绪状态
export const getScannerReadyStatus = async () => {
  try {
    const response = await api.get('/api/v1/scanner/ready-status')
    return response.data
  } catch (error) {
    console.error('获取扫码枪状态失败:', error)
    throw error
  }
}

// 获取项目数据
export const getProjects = async () => {
  try {
    const response = await api.get('/api/v1/projects/list')
    return response.data
  } catch (error) {
    console.error('获取项目数据失败:', error)
    throw error
  }
}

// 保存项目数据
export const saveProjects = async (projects) => {
  try {
    const response = await api.post('/api/v1/projects/save', projects)
    return response.data
  } catch (error) {
    console.error('保存项目数据失败:', error)
    throw error
  }
}

// 上传测试结果
export const uploadTestResults = async (testResultData) => {
  try {
    const response = await api.post('/api/v1/test-results/upload', testResultData)
    return response.data
  } catch (error) {
    console.error('上传测试结果失败:', error)
    throw error
  }
}

export default api